
/*
* 二维数组转稀疏数组
* */

import java.io.*;

public class SparseArr {
    public static void main(String[] args) throws IOException {
        //创建一个二维数组,动态初始化，默认值都为零
        int[][] ints = new int[15][15];
        //给二维数组赋3个值
        ints[4][11]=1;
        ints[11][4]=2;

        System.out.println("----------原始二维数组-------------");
        //增强For循环遍历
        int  sum=0;
        for (int[] row : ints) {
            for (int i : row) {
                if (i!=0){
                    sum++;
                }
                System.out.printf("%d\t",i);
            }
            System.out.println();
        }
        //创建对应的稀疏数组
        System.out.println("除了0的数="+sum);
        //初始化稀疏数组
        int[][] sparseArr = new int[sum + 1][3];
        //第一行放原始二维数组的行数和列数和有效值的个数
        sparseArr [0][0]=ints.length;
        sparseArr [0][1]=ints[0].length;
        sparseArr [0][2]=sum;
        int count=1;
        //将原始二维数组中的有效数据传给稀疏数组
        for (int i = 0; i < ints.length; i++) {
            for (int j = 0; j < ints[0].length; j++) {
                 if (ints[i][j]!=0){
                     sparseArr [count][0]=i;
                     sparseArr [count][1]=j;
                     sparseArr [count][2]=ints[i][j];
                     count++;
                 }
            }
        }
        System.out.println("----------稀疏数组-------------");
        System.out.println();
        for (int[] ints1 : sparseArr) {
            for (int i : ints1) {
                System.out.printf("%d\t",i);
            }
            System.out.println();
        }
        //将稀疏数组保存到文件中
        FileOutputStream fileOutputStream = new FileOutputStream(new File("sparseArr.text"));
        for (int[] ints1 : sparseArr) {
            for (int i : ints1) {
                 //int 类型是4个字节，字节流每次存储一个字节写入后会产生乱码
                fileOutputStream.write((String.valueOf(i)+",").getBytes());
            }
            fileOutputStream.write("\n".getBytes());
        }


        BufferedReader bufferedReader = new BufferedReader(new FileReader("sparseArr.text"));
        String line = null;
        int c = 0;
        String row = null;
        String col = null;

        int[][] Array = null;
        //读取每一行的数据
        while((line = bufferedReader.readLine())!= null){
            c++;
            if(c==1){//稀疏矩阵的第一行
                String[] array = line.split(",");//以，为分割读取文件
                row = array[0];
                col = array[1];
                Array = new int[Integer.parseInt(row)][Integer.parseInt(col)];
            }else {
                String[] array = line.split(",");
                String hang = array[0];
                String lie = array[1];
                String data = array[2];
                Array[Integer.parseInt(hang)][Integer.parseInt(lie)] = Integer.parseInt(data);
            }
        }
        for (int[] r:Array){
            for (int item:r){
                System.out.printf("%d\t",item);
            }
            System.out.println();
        }
    }
}


